﻿using System;

using System.Text.RegularExpressions;
using System.IO;
using System.Text;
using System.Net;
using System.Collections;
using System.Security.Cryptography;

namespace HF.Software.ClassLib
{
    public class StrHelper
    {
        private static string passWord;	//加密字符串

        /// <summary>
        /// 查找字符串是否存在于数组中
        /// </summary>
        /// <param name="item"></param>
        /// <param name="str"></param>
        /// <returns></returns>
        public static bool StrInArray(string[] item, string str)
        {
            #region
            foreach (string s in item)
            {
                if (string.Equals(s, str))
                {
                    return true;
                }
            }
            return false;
            #endregion
        }

        /// <summary>
        /// 返回文本编辑器替换后的字符串
        /// </summary>
        /// <param name="str">要替换的字符串</param>
        /// <returns></returns>
        static public string GetHtmlEditReplace(string str)
        {
            #region
            return str.Replace("'", "’").Replace("&nbsp;", " ").Replace(",", "，").Replace("%", "％").
                Replace("script", "").Replace(".js", "");
            #endregion
        }

        /// <summary>
        /// byte转16位
        /// </summary>
        /// <param name="InBytes"></param>
        /// <returns></returns>
        public static string ByteToString(byte[] InBytes)
        {
            StringBuilder sb = new StringBuilder();

            //兼容10版芯片号解码 140317 LiuHe            
            //foreach (byte InByte in InBytes)
            //{
            //    sb.Append(String.Format("{0:X2}", InByte));
            //}
            for (int i = 0; i < InBytes.Length; i++)
            {
                string str = String.Format("{0:X2}", InBytes[i]);
                //第三位 11 屏蔽 140317 LiuHe  
                if (i == 2 && str == "11")
                {
                }
                else
                {
                    sb.Append(str);
                }
            }

            return sb.ToString();
        }

        /// <summary>
        /// 获取字符串长度
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static int GetStringLength(string str)
        {
            Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
            char[] stringChar = str.ToCharArray();
            StringBuilder sb = new StringBuilder();
            int nLength = 0;
            for (int i = 0; i < stringChar.Length; i++)
            {
                if (regex.IsMatch((stringChar[i]).ToString()))
                {
                    sb.Append(stringChar[i]);
                    nLength += 2;
                }
                else
                {
                    sb.Append(stringChar[i]);
                    nLength = nLength + 1;
                }

            }

            return nLength;

        }

        /// <summary>
        /// 截取字符串优化版
        /// </summary>
        /// <param name="stringToSub">所要截取的字符串</param>
        /// <param name="length">截取字符串的长度</param>
        /// <returns></returns>
        public static string GetFirstString(string stringToSub, int length)
        {
            #region
            Regex regex = new Regex("[\u4e00-\u9fa5]+", RegexOptions.Compiled);
            char[] stringChar = stringToSub.ToCharArray();
            StringBuilder sb = new StringBuilder();
            int nLength = 0;
            bool isCut = false;
            for (int i = 0; i < stringChar.Length; i++)
            {
                if (regex.IsMatch((stringChar[i]).ToString()))
                {
                    sb.Append(stringChar[i]);
                    nLength += 2;
                }
                else
                {
                    sb.Append(stringChar[i]);
                    nLength = nLength + 1;
                }

                if (nLength > length)
                {
                    isCut = true;
                    break;
                }
            }
            if (isCut)
                return sb.ToString() + "..";
            else
                return sb.ToString();
            #endregion
        }

        /// <summary>
        /// 过滤输入信息
        /// </summary>
        /// <param name="text">内容</param>
        /// <param name="maxLength">最大长度</param>
        /// <returns></returns>
        public static string InputText(string text, int maxLength)
        {
            #region
            text = text.Trim();
            if (string.IsNullOrEmpty(text))
                return string.Empty;
            if (text.Length > maxLength)
                text = text.Substring(0, maxLength);
            text = Regex.Replace(text, "[\\s]{2,}", " ");	//two or more spaces
            text = Regex.Replace(text, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n");	//<br>
            text = Regex.Replace(text, "(\\s*&[n|N][b|B][s|S][p|P];\\s*)+", " ");	//&nbsp;
            text = Regex.Replace(text, "<(.|\\n)*?>", string.Empty);	//any other tags
            text = text.Replace("'", "''");
            return text;
            #endregion
        }

        #region 生成指定位数随机数
        private static char[] constant =   
          {   
            '0','1','2','3','4','5','6','7','8','9',   
            'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',   
            'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'   
          };

        public static string GenerateRandom(int Length)
        {
            System.Text.StringBuilder newRandom = new System.Text.StringBuilder(62);
            Random rd = new Random();
            for (int i = 0; i < Length; i++)
            {
                newRandom.Append(constant[rd.Next(62)]);
            }
            return newRandom.ToString();
        }

        public static string GetNumRandom(int Length)
        {
            System.Text.StringBuilder newRandom = new System.Text.StringBuilder(10);
            char[] NumStr = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
            Random rd = new Random();
            for (int i = 0; i < Length; i++)
            {
                newRandom.Append(constant[rd.Next(10)]);
            }
            return newRandom.ToString();
        }
        #endregion

        /// <summary>
        /// 获取汉字第一个拼音
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        static public string GetSpells(string input)
        {
            #region
            int len = input.Length;
            string reVal = "";
            for (int i = 0; i < len; i++)
            {
                reVal += GetSpell(input.Substring(i, 1));
            }
            return reVal;
            #endregion
        }

        static public string GetSpell(string cn)
        {
            #region
            byte[] arrCN = Encoding.Default.GetBytes(cn);
            if (arrCN.Length > 1)
            {
                int area = (short)arrCN[0];
                int pos = (short)arrCN[1];
                int code = (area << 8) + pos;
                int[] areacode = { 45217, 45253, 45761, 46318, 46826, 47010, 47297, 47614, 48119, 48119, 49062, 49324, 49896, 50371, 50614, 50622, 50906, 51387, 51446, 52218, 52698, 52698, 52698, 52980, 53689, 54481 };
                for (int i = 0; i < 26; i++)
                {
                    int max = 55290;
                    if (i != 25) max = areacode[i + 1];
                    if (areacode[i] <= code && code < max)
                    {
                        return Encoding.Default.GetString(new byte[] { (byte)(65 + i) });
                    }
                }
                return "?";
            }
            else return cn;
            #endregion
        }


        /// <summary>
        /// 半角转全角
        /// </summary>
        /// <param name="BJstr"></param>
        /// <returns></returns>
        static public string GetQuanJiao(string BJstr)
        {
            #region
            char[] c = BJstr.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                byte[] b = System.Text.Encoding.Unicode.GetBytes(c, i, 1);
                if (b.Length == 2)
                {
                    if (b[1] == 0)
                    {
                        b[0] = (byte)(b[0] - 32);
                        b[1] = 255;
                        c[i] = System.Text.Encoding.Unicode.GetChars(b)[0];
                    }
                }
            }

            string strNew = new string(c);
            return strNew;

            #endregion
        }

        /// <summary>
        /// 全角转半角
        /// </summary>
        /// <param name="QJstr"></param>
        /// <returns></returns>
        static public string GetBanJiao(string QJstr)
        {
            #region
            char[] c = QJstr.ToCharArray();
            for (int i = 0; i < c.Length; i++)
            {
                byte[] b = System.Text.Encoding.Unicode.GetBytes(c, i, 1);
                if (b.Length == 2)
                {
                    if (b[1] == 255)
                    {
                        b[0] = (byte)(b[0] + 32);
                        b[1] = 0;
                        c[i] = System.Text.Encoding.Unicode.GetChars(b)[0];
                    }
                }
            }
            string strNew = new string(c);
            return strNew;
            #endregion
        }

        /// <summary>
        /// 字符串加密
        /// </summary>
        /// <param name="PasswordString">要加密的字符串</param>
        /// <param name="PasswordFormat">要加密的类别</param>
        /// <returns></returns>
        static public string EncryptMd5Password(string PasswordString)
        {
            #region

            PasswordString = PasswordString.ToLower();
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(PasswordString)));
            t2 = t2.Replace("-", "").ToUpper();
            return t2;


            #endregion
        }

        /// <summary>
        /// 字符串转换为 html
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string StringToHtml(string str)
        {
            #region
            str = str.Replace("&", "&amp;");
            str = str.Replace(" ", "&nbsp;");
            str = str.Replace("'", "''");
            str = str.Replace("\"", "&quot;");
            str = str.Replace(" ", "&nbsp;");
            str = str.Replace("<", "&lt;");
            str = str.Replace(">", "&gt;");
            str = str.Replace("\r\n", "<br>");

            return str;
            #endregion
        }

        /// <summary>
        /// html转换成字符串
        /// </summary>
        /// <param name="strHtml"></param>
        /// <returns></returns>
        public static string HtmlToString(string strHtml)
        {
            #region
            strHtml = strHtml.Replace("<br>", "\r\n");
            strHtml = strHtml.Replace(@"<br />", "\r\n");
            strHtml = strHtml.Replace(@"<br/>", "\r\n");
            strHtml = strHtml.Replace("&gt;", ">");
            strHtml = strHtml.Replace("&lt;", "<");
            strHtml = strHtml.Replace("&nbsp;", " ");
            strHtml = strHtml.Replace("&quot;", "\"");

            strHtml = Regex.Replace(strHtml, @"<\/?[^>]+>", "", RegexOptions.IgnoreCase);

            return strHtml;
            #endregion
        }


        public static string ClearHtml(string HtmlString)
        {
            string pn = "(</?.*?/?>)";
            HtmlString = Regex.Replace(HtmlString, pn, "");
            return HtmlString;
        }



        #region 获取N行数据
        /// <summary>
        /// 取指定行数数据
        /// </summary>
        /// <param name="str">传入的待取字符串</param>
        /// <param name="rowsnum">指定的行数</param>
        /// <param name="strnum">每行的英文字符数或字节数</param>
        /// <returns></returns>
        public static string GetContent(string str, int rowsnum, int strnum)
        {
            //1计算内容块           
            string content = str.Replace("\r\n", "§");
            string[] strContent = content.Split(Convert.ToChar("§"));

            int strCount = rowsnum * strnum;
            int cutrow = rowsnum - strContent.Length;
            cutrow = rowsnum > 10 ? rowsnum : 10;
            int pStrCount;
            string setOkStr = "";


            //2对内容块进行
            for (int i = 0; i < strContent.Length; i++)
            {
                pStrCount = System.Text.Encoding.Default.GetBytes(strContent[i]).Length;
                if (pStrCount < strCount)
                {
                    setOkStr += strContent[i] + "<br>";
                    rowsnum -= Convert.ToInt32(Math.Ceiling((double)pStrCount / (double)strnum));
                    strCount = rowsnum * strnum;
                }
                else
                {
                    if (rowsnum > 0)
                    {
                        setOkStr += CutStr(strContent[i], rowsnum * strnum, cutrow);
                    }
                    else
                    {
                        //减去rowsnum是为了避免有些行长度为90,有的为89的现像
                        setOkStr = setOkStr.Substring(0, setOkStr.Length - cutrow / 2) + "...";
                    }
                    break;
                }
            }

            setOkStr = setOkStr.Replace("  ", "　"); //软（半角）空格转硬（全角)空格
            return setOkStr;

        }

        //字符串截取函数
        private static string CutStr(string str, int length, int rowsnum)
        {
            if (System.Text.Encoding.Default.GetBytes(str).Length < length)
                return str;

            length = length - rowsnum;
            int i = 0, j = 0;
            foreach (char chr in str)
            {
                if ((int)chr > 127)
                    i += 2;
                else
                    i++;
                if (i > length)
                {
                    str = str.Substring(0, j) + "...";
                    break;
                }
                j++;
            }
            return str;

        }
        #endregion

        #region 得到整型
        public static int ConvertToInt(string Str)
        {
            return Str.Trim() == string.Empty ? 0 : int.Parse(Str);
        }

        public static int GetInt(object o)
        {
            #region
            if (o == DBNull.Value || o == null)
                return 0;
            else
                return Convert.ToInt32(o);
            #endregion
        }
        #endregion

        #region 得到浮点型
        public static double ConvertToDouble(string Str)
        {
            return string.IsNullOrEmpty(Str) ? 0 : Convert.ToDouble(Str);
        }
        #endregion

        /// <summary>
        /// 转化成时间类型
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static object ConvertDate(object o)
        {
            DateTime dt;
            if (DateTime.TryParse(o.ToString(), out dt))
                return dt;
            else
                return DBNull.Value;
        }

        #region 闭合HTML代码
        public static string CloseHTML(string str)
        {
            string[] HtmlTag = new string[] { "p", "div", "span", "table", "ul", "font", "b", "u", "i", "a", "h1", "h2", "h3", "h4", "h5", "h6" };
            if (str == string.Empty)
                return str;

            for (int i = 0; i < HtmlTag.Length; i++)
            {
                int OpenNum = 0, CloseNum = 0;
                Regex re = new Regex("<" + HtmlTag + "[^>]*" + ">", RegexOptions.IgnoreCase);
                MatchCollection m = re.Matches(str);
                OpenNum = m.Count;
                re = new Regex("</" + HtmlTag + ">", RegexOptions.IgnoreCase);
                m = re.Matches(str);
                CloseNum = m.Count;

                for (int j = 0; j < OpenNum - CloseNum; j++)
                {
                    str += "</" + HtmlTag + ">";
                }
            }

            return str;
        }
        #endregion

        /// <summary>
        /// 得到192.248.23.*的IP
        /// </summary>
        /// <param name="Str">IP地址</param>
        /// <returns></returns>
        public static string GetSortIp(string Str)
        {
            int x = Str.LastIndexOf('.') - 1;
            return Str.Substring(0, x) + "*.*";
        }

        #region 获取远程页面内容
        public static string GetUrlData(string url, string encode)
        {
            string result = string.Empty;
            HttpWebRequest myHttpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            //10秒超时
            myHttpWebRequest.Timeout = 5 * 1000;
            myHttpWebRequest.Method = "GET";
            myHttpWebRequest.Headers.Add(HttpRequestHeader.AcceptLanguage, "en-US ");
            myHttpWebRequest.Headers.Add(HttpRequestHeader.AcceptEncoding, encode);
            myHttpWebRequest.UserAgent = "Mozilla/4.0(compatible;MSIE 7.0;Windows NT 5.2;.NET CLR 1.1.4322;.NET CLR 2.0.50727;InfoPath.1;.NET CLR 3.0.04506.30)";
            HttpWebResponse response = (HttpWebResponse)myHttpWebRequest.GetResponse();
            if (response.StatusCode == HttpStatusCode.OK)
            {
                Stream responseStream = response.GetResponseStream();
                StreamReader sr = new StreamReader(responseStream, Encoding.GetEncoding(encode));
                result = sr.ReadToEnd();
                sr.Close();
                responseStream.Close();
            }
            response.Close();
            return result;
        }
        #endregion

        /// <summary>
        /// 判断页面是否存在
        /// </summary>
        /// <param name="sURL"></param>
        /// <returns></returns>
        public static bool UrlExist(string sURL)
        {
            #region
            try
            {
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(sURL);
                //WebProxy   proxy   =   new   WebProxy("your   proxy   server",   8080);   
                //request.Proxy   =   proxy;   
                request.Method = "HEAD";
                request.AllowAutoRedirect = false;
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                bool result = false;
                switch (response.StatusCode)
                {
                    case HttpStatusCode.OK:
                        result = true;
                        break;
                    case HttpStatusCode.Moved:
                        break;
                    case HttpStatusCode.NotFound:
                        break;
                }
                response.Close();
                return result;
            }
            catch
            {
                return false;
            }
            #endregion
        }

        #region 获取字串中的链接
        /// <summary>
        /// 获取字串中的链接
        /// </summary>
        /// <param name="HtmlCode"></param>
        /// <returns></returns>
        public static ArrayList GetPageUrl(string HtmlCode)
        {
            ArrayList my_list = new ArrayList();
            string p = @"http://([\w-]+\.)+[\w-]+(/[\w- ./?%&=]*)?";
            Regex re = new Regex(p, RegexOptions.IgnoreCase);
            MatchCollection mc = re.Matches(HtmlCode);

            for (int i = 0; i <= mc.Count - 1; i++)
            {
                string name = mc[i].ToString();
                if (!my_list.Contains(name))//排除重复URL
                {
                    my_list.Add(name);
                }
            }
            return my_list;
        }
        #endregion


        /// <summary>
        /// 将 Stream 转化成 string
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string ConvertStreamToString(Stream s)
        {
            #region
            string strResult = "";
            StreamReader sr = new StreamReader(s, Encoding.UTF8);

            Char[] read = new Char[256];

            // Read 256 charcters at a time.    
            int count = sr.Read(read, 0, 256);

            while (count > 0)
            {
                // Dump the 256 characters on a string and display the string onto the console.
                string str = new String(read, 0, count);
                strResult += str;
                count = sr.Read(read, 0, 256);
            }


            // 释放资源
            sr.Close();

            return strResult;
            #endregion
        }

        /// <summary>
        /// 对传递的参数字符串进行处理，防止注入式攻击
        /// </summary>
        /// <param name="str">传递的参数字符串</param>
        /// <returns>String</returns>
        public static string ConvertSql(string str)
        {
            #region
            str = str.Trim();
            str = str.Replace("'", "''");
            str = str.Replace(";--", "");
            str = str.Replace("=", "");
            str = str.Replace(" or ", "");
            str = str.Replace(" and ", "");

            return str;
            #endregion
        }


        /// <summary>
        /// 获取数组元素的合并字符串
        /// </summary>
        /// <param name="stringArray"></param>
        /// <returns></returns>
        public static string GetArrayString(string[] stringArray)
        {
            #region
            string totalString = null;
            for (int i = 0; i < stringArray.Length; i++)
            {
                totalString = totalString + stringArray[i];
            }
            return totalString;
            #endregion
        }

        /// <summary>
        /// 将指定字符串中的汉字转换为拼音首字母的缩写，其中非汉字保留为原字符
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public static string ConvertSpellFirst(string text)
        {
            #region
            char pinyin;
            byte[] array;
            StringBuilder sb = new StringBuilder(text.Length);
            foreach (char c in text)
            {
                pinyin = c;
                array = Encoding.Default.GetBytes(new char[] { c });

                if (array.Length == 2)
                {
                    int i = array[0] * 0x100 + array[1];

                    #region 条件匹配
                    if (i < 0xB0A1) pinyin = c;
                    else
                        if (i < 0xB0C5) pinyin = 'a';
                        else
                            if (i < 0xB2C1) pinyin = 'b';
                            else
                                if (i < 0xB4EE) pinyin = 'c';
                                else
                                    if (i < 0xB6EA) pinyin = 'd';
                                    else
                                        if (i < 0xB7A2) pinyin = 'e';
                                        else
                                            if (i < 0xB8C1) pinyin = 'f';
                                            else
                                                if (i < 0xB9FE) pinyin = 'g';
                                                else
                                                    if (i < 0xBBF7) pinyin = 'h';
                                                    else
                                                        if (i < 0xBFA6) pinyin = 'g';
                                                        else
                                                            if (i < 0xC0AC) pinyin = 'k';
                                                            else
                                                                if (i < 0xC2E8) pinyin = 'l';
                                                                else
                                                                    if (i < 0xC4C3) pinyin = 'm';
                                                                    else
                                                                        if (i < 0xC5B6) pinyin = 'n';
                                                                        else
                                                                            if (i < 0xC5BE) pinyin = 'o';
                                                                            else
                                                                                if (i < 0xC6DA) pinyin = 'p';
                                                                                else
                                                                                    if (i < 0xC8BB) pinyin = 'q';
                                                                                    else
                                                                                        if (i < 0xC8F6) pinyin = 'r';
                                                                                        else
                                                                                            if (i < 0xCBFA) pinyin = 's';
                                                                                            else
                                                                                                if (i < 0xCDDA) pinyin = 't';
                                                                                                else
                                                                                                    if (i < 0xCEF4) pinyin = 'w';
                                                                                                    else
                                                                                                        if (i < 0xD1B9) pinyin = 'x';
                                                                                                        else
                                                                                                            if (i < 0xD4D1) pinyin = 'y';
                                                                                                            else
                                                                                                                if (i < 0xD7FA) pinyin = 'z';
                    #endregion
                }

                sb.Append(pinyin);
            }

            return sb.ToString();
            #endregion
        }

        public static Byte[] strToBytes(string strInfo)
        {
            return ASCIIEncoding.ASCII.GetBytes(strInfo);
        }

        #region 获取之间的字符串
        /// <summary>
        /// 获取之间的字符串
        /// </summary>
        /// <param name="strBody">源字串</param>
        /// <param name="strFirst">开头的串</param>
        /// <param name="strEnd">结尾的串</param>
        /// <returns></returns>
        public static string GetBetweenStr(string strBody, string strFirst, string strEnd)
        {
            return GetBetweenStr(0, strBody, strFirst, strEnd);
        }

        /// <summary>
        /// 获取之间的字符串
        /// </summary>
        /// <param name="startPosition">开始位置</param>
        /// <param name="strBody">源字串</param>
        /// <param name="strFirst">开头的串</param>
        /// <param name="strEnd">结尾的串</param>
        /// <returns></returns>
        public static string GetBetweenStr(int startPosition, string strBody, string strFirst, string strEnd)
        {
            int first = strBody.IndexOf(strFirst, startPosition);
            int firstLen = strFirst.Length;
            if (first != -1)
            {
                int end = strBody.IndexOf(strEnd, first);
                if (end != -1)//子串在源串中不存在
                {
                    return strBody.Substring(first + firstLen, end - first - firstLen);
                }
                else
                {
                    return string.Empty;
                }
            }
            else
            {
                return string.Empty;
            }
        }
        #endregion

        public static string GetTimeMessage()
        {
            DateTime dt = DateTime.Now;
            if (dt.Hour <= 4)
            {
                return "深夜";
            }
            else if (dt.Hour <= 6)
            {
                return "凌晨";
            }
            else if (dt.Hour <= 8)
            {
                return "早上";
            }
            else if (dt.Hour < 12)
            {
                return "上午";
            }
            else if (dt.Hour == 12)
            {
                return "中午";
            }
            else if (dt.Hour <= 18)
            {
                return "下午";
            }
            else if (dt.Hour <= 22)
            {
                return "晚上";
            }
            else
            {
                return "深夜";
            }
        }

        /// <summary>
        /// 取数值型
        /// </summary>
        /// <param name="StrSource"></param>
        /// <returns></returns>
        public static bool IntYz(string StrSource)
        {
            return Regex.IsMatch(StrSource, @"^[0-9\.][0-9\.]*$");


        }

        /// <summary>
        /// 中英文混合字符串对齐 左侧填充
        /// </summary>
        /// <param name="str"></param>
        /// <param name="totalByteCount"></param>
        /// <param name="c"></param>
        /// <returns></returns>
        public static string PadLeftEx(string str, int totalByteCount, char c)
        {
            Encoding coding = Encoding.GetEncoding("gb2312");
            int dcount = 0;
            foreach (char ch in str.ToCharArray())
            {
                if (coding.GetByteCount(ch.ToString()) == 2)
                    dcount++;
            }
            string w = str.PadLeft(totalByteCount - dcount, c);
            return w;
        }

        /// <summary>
        /// 中英文混合字符串对齐 右侧填充
        /// </summary>
        /// <param name="str"></param>
        /// <param name="totalByteCount"></param>
        /// <param name="c"></param>
        /// <returns></returns>
        public static string PadRightEx(string str, int totalByteCount, char c)
        {
            Encoding coding = Encoding.GetEncoding("gb2312");
            int dcount = 0;
            if (str == null)
            {
                str = "";
            }
            foreach (char ch in str.ToCharArray())
            {
                if (coding.GetByteCount(ch.ToString()) == 2)
                    dcount++;
            }
            string w = str.PadRight(totalByteCount - dcount, c);
            return w;
        }

        /// <summary>
        /// 字符串转ASC串
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GetAscString(string str)
        {
            string result = string.Empty;
            if (str != null)
            {
                foreach (char c in str)
                {
                    result += Convert.ToString((int)c, 16);
                }
            }
            return str;
        }
        /// <summary>
        /// 获取中文首字母
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string CVT(string str)
        {
            if (str.CompareTo("吖") < 0)
            {
                string s = str.Substring(0, 1).ToUpper();
                if (char.IsNumber(s, 0))
                {
                    return "0";
                }
                else
                {
                    return s;
                }
            }
            else if (str.CompareTo("八") < 0)
            {
                return "A";
            }
            else if (str.CompareTo("嚓") < 0)
            {
                return "B";
            }
            else if (str.CompareTo("咑") < 0)
            {
                return "C";
            }
            else if (str.CompareTo("妸") < 0)
            {
                return "D";
            }
            else if (str.CompareTo("发") < 0)
            {
                return "E";
            }
            else if (str.CompareTo("旮") < 0)
            {
                return "F";
            }
            else if (str.CompareTo("铪") < 0)
            {
                return "G";
            }
            else if (str.CompareTo("讥") < 0)
            {
                return "H";
            }
            else if (str.CompareTo("咔") < 0)
            {
                return "J";
            }
            else if (str.CompareTo("垃") < 0)
            {
                return "K";
            }
            else if (str.CompareTo("嘸") < 0)
            {
                return "L";
            }
            else if (str.CompareTo("拏") < 0)
            {
                return "M";
            }
            else if (str.CompareTo("噢") < 0)
            {
                return "N";
            }
            else if (str.CompareTo("妑") < 0)
            {
                return "O";
            }
            else if (str.CompareTo("七") < 0)
            {
                return "P";
            }
            else if (str.CompareTo("亽") < 0)
            {
                return "Q";
            }
            else if (str.CompareTo("仨") < 0)
            {
                return "R";
            }
            else if (str.CompareTo("他") < 0)
            {
                return "S";
            }
            else if (str.CompareTo("哇") < 0)
            {
                return "T";
            }
            else if (str.CompareTo("夕") < 0)
            {
                return "W";
            }
            else if (str.CompareTo("丫") < 0)
            {
                return "X";
            }
            else if (str.CompareTo("帀") < 0)
            {
                return "Y";
            }
            else if (str.CompareTo("咗") < 0)
            {
                return "Z";
            }
            else
            {
                return "0";
            }
        }
    }
}
